<script setup>
import {
    Edit,
    Delete
} from '@element-plus/icons-vue'

import { ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {  memberListService ,addMemberService, updateMemberService, deleteMemberService } from '@/api/member.js'
import {lessonListService} from '@/api/lesson.js'

//会员列表数据模型
const member = ref([
    {
        "id": 1,
        "memberAccount": "202009867",
        "name": "张三",
        "gender": "男",
        "age": "23",
        "height": "180",
        "weight": "70",
        "phone": "15212345678",
        "createTime": "2020-06-05",
        "classTime": "30",
    }
]);
//条件搜索模型
const name = ref('');
const gender = ref('');
//分页条数据模型
const page = ref(1)//当前页
const total = ref(20)//总条数
const pageSize = ref(10)//每页条数

//获取会员列表数据
const memberList = async () => {
    let params = {
        page: page.value,
        pageSize: pageSize.value,
        name: name.value ? name.value : null,
        gender: gender.value ? gender.value : null
    }
    let result = await memberListService(params)

    //渲染视图
    total.value = result.data.total;
    member.value = result.data.records;
}
//调用函数查询
memberList();

//当每页条数发生了变化，调用此函数
const handleSizeChange = (size) => {
    pageSize.value = size
    memberList();
}
//当前页码发生变化，调用此函数
const handleCurrentChange = (num) => {
    page.value = num
    memberList();
}

//课程分类数据模型
const lessons = ref({
    "id": 1,
    "name": "增肌",
})
//课程数据回写
const lessonList =async () =>{
    let params = {
        page: page.value,
        pageSize: pageSize.value,
    }
    let result = await lessonListService(params);
    lessons.value = result.data.records
    console.log(lessons.value)
}
lessonList();
//添加、修改会员表单模型
const memberForm = ref({
    name: '',
    gender: '',
    age: '',
    height: '',
    weight: '',
    phone: '',
    classTime: '',
    lessonId: ''
})
//添加、修改会员的表单校验模型
const Rules = ref({
    name: [
        { required: true, message: '请输入用户账号', trigger: 'blur' }
    ],
    gender: [
        { required: true, message: '请选择', trigger: 'blur' }
    ],
    age: [
        { required: true, message: '请输入年龄', trigger: 'blur' },
        { min: 1, max: 2, message: '年龄必须为1~99之间', trigger: 'blur' }
    ],
    height: [
        { required: true, message: '请输入身高', trigger: 'blur' },
    ],
    weight: [
        { required: true, message: '请输入体重', trigger: 'blur' },
    ],
    phone: [
        { required: true, message: '请输入联系方式', trigger: 'blur' },
        { pattern: /^1\d{10}$/, message: '电话号码为11位', trigger: 'blur' }
    ],
    classTime: [
        { required: true, message: '请输入购买课时', trigger: 'blur' }
    ],
    lessonId: [
        { required: true, message: '请选择', trigger: 'blur' }
    ]
})
//默认不显示抽屉
const visibleDrawer = ref(false)
//为抽屉添加响应数据
const addMemberRef = ref()
//后台调用添加会员接口
const onAdd = async () => {
    //点击添加按钮后再进行二次校验
    await addMemberRef.value?.validate().catch((err) => { ElMessage.error("校验失败"); return Promise.reject(err) })
    let result = await addMemberService(memberForm.value);
    ElMessage.success(result.msg ? result.msg : '添加成功')
    //让抽屉消失
    visibleDrawer.value = false
    //刷新列表
    memberList();
}
//刷新抽屉表单
const clearMemberForm = () => {
    memberForm.value = {
        name: '',
        gender: '',
        age: '',
        height: '',
        weight: '',
        phone: '',
        classTime: '',
        lessonId:''
    }
}
//取消添加
const cancelDrawer = () => {
    visibleDrawer.value = false
}


//默认不显示对话框
const visibleDialog = ref(false)
//展示编辑对话框弹窗
const showDialog = (row) => {
    clearMemberForm()
    visibleDialog.value = true
    //给编辑框回写原先信息
    memberForm.value.name = row.name
    memberForm.value.gender = row.gender
    memberForm.value.age = row.age
    memberForm.value.height = row.height
    memberForm.value.weight = row.weight
    memberForm.value.phone = row.phone
    memberForm.value.classTime = row.classTime
    memberForm.value.lessonId = row.lessonId
    //扩展模型添加id
    memberForm.value.id = row.id
}
//为对话框添加响应数据
const updateMemberRef = ref()
//后台调用修改会员接口
const onUpdate = async () => {
    //点击修改后再进行二次校验
    await updateMemberRef.value?.validate().catch((err) => { ElMessage.error("校验失败"); return Promise.reject(err) })
    let result = await updateMemberService(memberForm.value);
    ElMessage.success(result.msg ? result.msg : '修改成功')
    //让对话框消失
    visibleDialog.value = false
    //刷新列表
    memberList();
}

//取消修改
const cancelDialog = () => {
    visibleDialog.value = false
}

const deleteMember = (row) => {
    ElMessageBox.confirm(
        '确定要删除吗？',
        '提示',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(async () => {
            let result = await deleteMemberService(row.id);
            ElMessage({
                type: 'success',
                message: result.msg ? result.msg : '删除成功',
            })
            memberList();
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '取消操作',
            })
        })
}

</script>
<template>
    <el-card class="page-container">
        <template #header>
            <div class="header">
                <span>会员管理</span>
                <div class="extra">
                    <el-button type="primary" @click="visibleDrawer = true; clearMemberForm()">添加会员</el-button>
                </div>
            </div>
        </template>
        <!-- 搜索表单 -->
        <el-form inline>
            <el-form-item prefix-icon="name" label="会员姓名：">
                <el-input v-model="name" placeholder="请输入姓名"></el-input>
            </el-form-item>

            <el-form-item label="性别：">
                <el-select placeholder="请选择" v-model="gender">
                    <el-option label="男" value="1"></el-option>
                    <el-option label="女" value="2"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="memberList()">搜索</el-button>
                <el-button @click="name = ''; gender = ''">重置</el-button>
            </el-form-item>
        </el-form>
        <!-- 会员列表 -->
        <el-table :data="member" style="width: 100%">
            <el-table-column label="序号" width="100">
                <template v-slot="scope">
                    <!-- 序号实现自动增加且连续 -->
                    {{ (page - 1) * pageSize + scope.$index + 1 }}
                </template>
            </el-table-column>
            <el-table-column label="会员账号/卡号" prop="memberAccount" width="200"></el-table-column>
            <el-table-column label="姓名" prop="name"></el-table-column>
            <el-table-column label="性别" prop="gender" show-overflow-tooltip width="100">
                <!-- 将渲染的1，2转换为男，女 -->
                <template v-slot="scope">{{ scope.row.gender === 1 ? '男' : '女' }}</template>
            </el-table-column>
            <el-table-column label="年龄" prop="age" width="100"></el-table-column>
            <el-table-column label="身高" prop="height" width="100"></el-table-column>
            <el-table-column label="体重" prop="weight" width="100"></el-table-column>
            <el-table-column label="联系方式" prop="phone"></el-table-column>
            <el-table-column label="办卡时间" prop="createTime"></el-table-column>
            <el-table-column label="购买课时" prop="classTime"></el-table-column>
            <el-table-column label="操作" width="100">
                <template #default="{ row }">
                    <el-button :icon="Edit" circle plain type="primary" @click="showDialog(row)"></el-button>
                    <el-button :icon="Delete" circle plain type="danger" @click="deleteMember(row)"></el-button>
                </template>
            </el-table-column>
            <template #empty>
                <el-empty description="没有数据" />
            </template>
        </el-table>
        <!-- 分页条 -->
        <el-pagination v-model:current-page="page" v-model:page-size="pageSize" background
            layout="sizes,prev, pager,next,jumper,total" @size-change="handleSizeChange"
            @current-change="handleCurrentChange" :total="total">
        </el-pagination>

        <!-- 抽屉中嵌套添加表单 -->
        <el-drawer v-model="visibleDrawer" title="添加会员" direction="rtl">
            <div>
                <el-form ref="addMemberRef" :model="memberForm" :rules="Rules">
                    <el-form-item label="姓名" prop="name">
                        <el-input v-model="memberForm.name" autocomplete="off" />
                    </el-form-item>
                    <el-form-item label="性别" prop="gender">
                        <el-select placeholder="请选择" v-model="memberForm.gender">
                            <el-option label="男" value="1"></el-option>
                            <el-option label="女" value="2"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="年龄" prop="age">
                        <el-input type="number" v-model="memberForm.age" autocomplete="off" />
                    </el-form-item>
                    <el-form-item label="身高/cm" prop="height">
                        <el-input type="number" v-model="memberForm.height" autocomplete="off" />
                    </el-form-item>
                    <el-form-item label="体重/kg" prop="weight">
                        <el-input type="number" v-model="memberForm.weight" autocomplete="off" />
                    </el-form-item>
                    <el-form-item label="联系方式" prop="phone">
                        <el-input type="number" maxlength="11" v-model="memberForm.phone" autocomplete="off" />
                    </el-form-item>
                    <el-form-item label="购买课时/min" prop="classTime">
                        <el-input type="number" v-model="memberForm.classTime" autocomplete="off" />
                    </el-form-item>
                    <el-form-item label="课程：" prop="lessonId">
                        <el-select placeholder="请选择" v-model="memberForm.lessonId" >
                            <el-option v-for="l in lessons" :key="l.id" :label="l.name" :value="l.id">
                            </el-option>
                        </el-select>
                    </el-form-item>

                </el-form>
                <!-- 按钮设置 -->
                <div>
                    <el-button @click="cancelDrawer(); clearMemberForm()">取消</el-button>
                    <el-button type="primary" @click="onAdd">
                        添加
                    </el-button>
                </div>
            </div>
        </el-drawer>

        <!-- 对话框嵌套编辑表单 -->
        <el-dialog v-model="visibleDialog" title="修改会员">
            <div>
                <el-form ref="updateMemberRef" :model="memberForm" :rules="updateRules">
                    <el-form-item label="姓名" prop="name">
                        <el-input v-model="memberForm.name" autocomplete="off" />
                    </el-form-item>
                    <el-form-item label="性别" prop="gender">
                        <el-select placeholder="请选择" v-model="memberForm.gender">
                            <el-option label="男" value="1"></el-option>
                            <el-option label="女" value="2"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="年龄" prop="age">
                        <el-input type="number" v-model="memberForm.age" autocomplete="off" />
                    </el-form-item>
                    <el-form-item label="身高/cm" prop="height">
                        <el-input type="number" v-model="memberForm.height" autocomplete="off" />
                    </el-form-item>
                    <el-form-item label="体重/kg" prop="weight">
                        <el-input type="number" v-model="memberForm.weight" autocomplete="off" />
                    </el-form-item>
                    <el-form-item label="联系方式" prop="phone">
                        <el-input type="number" maxlength="11" v-model="memberForm.phone" autocomplete="off" />
                    </el-form-item>
                    <el-form-item label="购买课时/min" prop="classTime">
                        <el-input type="number" v-model="memberForm.classTime" autocomplete="off" />
                    </el-form-item>
                    <el-form-item label="课程：" prop="lessonId">
                        <el-select placeholder="请选择" v-model="memberForm.lessonId" >
                            <el-option v-for="l in lessons" :key="l.id" :label="l.name" :value="l.id">
                            </el-option>
                        </el-select>
                    </el-form-item>

                </el-form>
                <!-- 按钮设置 -->
                <div>
                    <el-button @click="cancelDialog(); clearMemberForm()">取消</el-button>
                    <el-button type="primary" @click="onUpdate">
                        修改
                    </el-button>
                </div>
            </div>
        </el-dialog>
    </el-card>
</template>

<style lang="scss" scoped>
.page-container {
    min-height: 100%;
    box-sizing: border-box;

    .header {
        display: flex;
        align-items: center;
        justify-content: space-between;
    }
}
</style>